package com.ton.utils;

import com.kypj.frame.common.log.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public abstract class LoopThread extends Thread {
    private static final Logger log = LoggerFactory.getLogger(LoopThread.class);
    protected boolean sendExecTime = true;

    @Override
    public void run() {

        while (true) {
            long loopTime = getLoopTime();
            try {
                long time = System.currentTimeMillis();
                execute();
                long t2 = System.currentTimeMillis() - time;
                if (sendExecTime && t2 > 30000) {
                    Log.error(this.getClass().getSimpleName() + " 任务执行耗时：" + t2);
                }
                if (loopTime < 0) {
                    break;
                }
                long sleepTime = loopTime - (System.currentTimeMillis() - time);
                if (sleepTime > 0) {
                    Thread.sleep(sleepTime);
                }


            } catch (Exception e) {
                Log.error(this.getClass().getSimpleName() + " 任务执行失败" + e.getMessage());
                log.error("", e);
                if (loopTime > 0) {
                    try {
                        Thread.sleep(loopTime);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    public abstract long getLoopTime();

    public abstract void execute() throws Exception;
}
